"use strict";

var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");

var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/concat"));

/**
 * 校验是否为正确的IP地址
 *
 * @since 1.1.0
 * @category 正则
 * @param {string} str 需要校验的字符串.
 * @param {object} config 配置参数.
 * @param {boolean} config.isDetail 是否返回详细信息, 为true时返回CheckResult, false时返回boolean 默认: false.
 * @param {string} config.type 地址类型，'IPv4'-仅支持IPv4，'IPv6'-仅支持IPv6，默认为空，匹配所有类型.
 *
 * @returns { boolean|CheckResult } 校验结果 或 结果对象.
 *
 * @typedef {object} CheckResult
 * @property {boolean} status 校验结果
 * @property {string} errorMsg 错误提示
 * @property {RexExp} reg 校验数据使用的RexExp对象
 *
 * @example
 *
 * z.isIpAddress('192.168.1.1')
 * // => true
 * z.isIpAddress('2001:0db8:85a3:0000:0000:8a2e:0370:7334')
 * // => true
 * z.isIpAddress('2001:0db8::8a2e:0370:7334')
 * // => true 简化的IPv6地址也能检验通过
 * z.isIpAddress('192.168.1.1', { type: 'IPv6' })
 * // => false
 * z.isIpAddress('192.168.1.256', { isDetail: true })
 * // { status: false, errorMsg: '格式错误!', reg: xxx }
 *
 */
function isIpAddress(str) {
  var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      _ref$isDetail = _ref.isDetail,
      isDetail = _ref$isDetail === void 0 ? false : _ref$isDetail,
      _ref$type = _ref.type,
      type = _ref$type === void 0 ? '' : _ref$type;

  var rt = {
    status: false,
    errorMsg: ''
  };

  if (typeof str !== 'string') {
    throw new Error('类型错误');
  }

  var regIPv4 = ['^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'];
  var regIPv6 = ['^([0-9a-fA-F]{1,4}:){7}([0-9a-fA-F]{1,4}|:)$|^::(?:[0-9a-fA-F]{1,4}:){0,5}[0-9a-fA-F]{1,4}$|^([0-9a-fA-F]{1,4}:){1,6}:$|^([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}$|^([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}$|^([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}$|^([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}$|^[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})$|^:((:[0-9a-fA-F]{1,4}){1,7}|:)$|^fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}$|^::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])$|^([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])$'];
  var regs = [];

  if (type.toLowerCase() === 'ipv4') {
    regs = regIPv4;
  } else if (type.toLowerCase() === 'ipv6') {
    regs = regIPv6;
  } else {
    regs = (0, _concat.default)(regIPv4).call(regIPv4, regIPv6);
  }

  rt.reg = new RegExp(regs.join('|'));

  if (!rt.reg.test(str)) {
    rt.errorMsg = '格式错误!';
  } else {
    rt.status = true;
  }

  return isDetail ? rt : rt.status;
}

module.exports = isIpAddress;